package com.jf3q.sup.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.sup.domain.*;
import com.jf3q.sup.dto.PurchaseDetailsDto;
import com.jf3q.sup.dto.PurchasesAddDto;
import com.jf3q.sup.dto.PurchasesPageDto;
import com.jf3q.sup.service.*;
import com.jf3q.sup.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author : 八九宸烨
 * @date : 退！
 */
@RestController
@RequestMapping("/purchases")
public class PurchasesController {

    @Autowired
    PurchasesService purchasesService;

    @Autowired
    PurchaseDetailsService purchaseDetailsService;

    @Autowired
    SuppliersService suppliersService;

    @Autowired
    ProductsService productsService;

    @Autowired
    InboundShipmentsService inboundShipmentsService;

    @PreAuthorize("hasAuthority('/purchases')")
    @PostMapping("/getPurchasesPage")
    public ResultVo getPurchasesPage(@RequestBody PurchasesPageDto pageDto) {
        Page page=purchasesService.findPageList(pageDto);
        return ResultVo.success("",page);
    }

    @PreAuthorize("hasAuthority('/purchases')")
    @PostMapping("/getSupplier")
    public ResultVo getSupplier(){
        List<Suppliers> suppliersList=suppliersService.list();
        return ResultVo.success("",suppliersList);
    }

    @PreAuthorize("hasAuthority('/purchases/add')")
    @PostMapping("/selPurOnSup/{sId}")
    public ResultVo selPurOnSup(@PathVariable Integer sId){
        List<Products> productsList=productsService.getList(sId);
        return ResultVo.success("", productsList);
    }

    @PreAuthorize("hasAuthority('/purchases/add')")
    @PostMapping("/addPurchases")
    public ResultVo addPurchases(@RequestBody PurchasesAddDto addDto){
        BigDecimal sum = BigDecimal.valueOf(0);
        for (PurchaseDetailsDto detailsDto : addDto.getDetailsDtoList()) {
            BigDecimal count= new BigDecimal(detailsDto.getQuantity());
            BigDecimal price = detailsDto.getPrice();
            BigDecimal smallTotal = count.multiply(price);
            sum=sum.add(smallTotal);
        }
        addDto.setTotalAmount(sum);

        Integer purId=purchasesService.addPurchases(addDto);
        addDto.setPurId(purId);
        purchaseDetailsService.addDetails(addDto);

        //---------更新入库和商品数量----------------
        InboundShipments inboundShipments = new InboundShipments();
        inboundShipments.setReceivedDate(addDto.getPurchaseDate());
        inboundShipments.setWarehouseId(1);
        inboundShipments.setPurchaseId(purId);
        inboundShipments.setCreatedAt(new Date(System.currentTimeMillis()));
        inboundShipmentsService.save(inboundShipments);

        //根据pId拿到
        for (PurchaseDetailsDto detailsDto : addDto.getDetailsDtoList()) {
            Products byId = productsService.getById(detailsDto.getProductId());
            Products products = new Products();
            products.setId(detailsDto.getProductId());
            products.setStockQuantity(detailsDto.getQuantity()+ byId.getStockQuantity());
            productsService.updateById(products);
        }
        return ResultVo.success("",null);
    }

    @PreAuthorize("hasAuthority('/purchases/delete')")
    @PostMapping("/delPurchase/{purId}")
    public ResultVo delPurchase(@PathVariable Integer purId){
        try {
            LambdaQueryWrapper<InboundShipments> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(InboundShipments::getPurchaseId,purId);
            inboundShipmentsService.remove(lambdaQueryWrapper);
            LambdaQueryWrapper<PurchaseDetails> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(PurchaseDetails::getPurchaseId,purId);
            purchaseDetailsService.remove(queryWrapper);
            purchasesService.removeById(purId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResultVo.success("", null);
    }
}
